//
//  CHSViewController.m
//  ZXCheckAppItunesVersionManager
//
//  Created by 海参 on 07/19/2021.
//  Copyright (c) 2021 海参. All rights reserved.
//

#import "CHSViewController.h"
#import <ZXCheckAppItunesVersionManager/ZXCheckAppItunesVersionManager.h>
#import <Masonry/Masonry.h>
#import <ZXMBProgressHUD/ZXMBProgressHUD.h>
#import <ZXCategoriesUtil/ZXCategoriesUtil.h>

@interface CHSViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, copy) NSArray *dataArray;
@property (nonatomic, assign) BOOL isWillUpdate;

@end

@implementation CHSViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"测试";
    [self setUI];
    [self addMas];
    [self setData];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setUI
{
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
}



- (void)addMas{
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {      make.left.mas_equalTo(self.view.mas_left).with.offset(15);
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.top.equalTo(self.view.mas_top).with.offset(0);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
}

#pragma mark - Data

- (void)setData
{
    NSArray *sectionArr = @[
        @{
            @"section":@"selector0",
            @"sectionTitle":@"刚进页面检查新版本",
            @"list":@[
              @{
                  @"tag":@"checkResult",
                  @"title":@""
              },
        ]},
        @{
            @"section":@"selector3",
            @"sectionTitle":@"itunes检查新版本带UI",
            @"list":@[
              @{
                  @"tag":@"ui-itunes",
                  @"title":@"itunes检查新版本"
              },
        ]},
    ];
    self.dataArray = sectionArr;
    [self requestData];
}

- (void)requestData
{
    [self requestCheckUpdate];
}


#pragma mark -

- (UITableView *)tableView
{
    if (!_tableView)
    {
        UITableView *view = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        view.backgroundColor = self.view.backgroundColor;
        view.delegate = self;
        view.dataSource = self;
//        view.separatorStyle = UITableViewCellSeparatorStyleNone;
        view.showsVerticalScrollIndicator = NO;
        [view registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
        view.estimatedRowHeight = 87;
        view.rowHeight = UITableViewAutomaticDimension;
        if (@available(iOS 15.0, *)) {
            view.sectionHeaderTopPadding = 0;
        } else {
            // Fallback on earlier versions
        }
        _tableView = view;
    }
    return _tableView;
}

#pragma mark - TableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSDictionary *dic = [self.dataArray objectAtIndex:section];
    NSArray *list = [dic objectForKey:@"list"];
    return list.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    if (indexPath.section == 0) {
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.textLabel.text = [NSString stringWithFormat:@"刚进页面检查新版本结果：%@",@(self.isWillUpdate)];
        return cell;
    }else{
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    NSDictionary *dic = [self.dataArray objectAtIndex:indexPath.section];
    NSArray *list = [dic objectForKey:@"list"];
    NSDictionary *rowDic = [list objectAtIndex:indexPath.row];
    NSString *value = [rowDic objectForKey:@"title"];
    cell.textLabel.text = value;
    cell.textLabel.numberOfLines = 0;
    return cell;
}

///不支持换行的
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    NSDictionary *dic =  [self.dataArray objectAtIndex:section];
    NSString *title = [dic objectForKey:@"sectionTitle"];
    return title;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return tableView.estimatedSectionHeaderHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [UIView new];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *dic = [self.dataArray objectAtIndex:indexPath.section];
    NSArray *list = [dic objectForKey:@"list"];
    NSDictionary *rowDic = [list objectAtIndex:indexPath.row];
    NSString *tag = [rowDic objectForKey:@"tag"];
    if ([tag isEqualToString:@"ui-itunes"]){
        [self requestCheckUpdateWithAlert];
    }
}



-(void)requestCheckUpdate
{
    [MBProgressHUD zx_showLoading];
    __weak __typeof(&*self)weakSelf = self;
    [ZXCheckAppItunesVersionManager checkAppStoreNewVersionWithAppleID:@"1512313756" success:^(BOOL isHaveNewVersion,CAIItunesModel *itunesModel) {
        weakSelf.isWillUpdate = isHaveNewVersion;
        [weakSelf.tableView reloadData];
        [MBProgressHUD zx_hideHUD];
        
    } failure:^(NSError * _Nonnull error) {
        [MBProgressHUD zx_showError:error.localizedDescription toView:nil];
    }];
}



-(void)requestCheckUpdateWithAlert
{
    [MBProgressHUD zx_showLoading];
    __weak __typeof(&*self)weakSelf = self;
    NSString *appId = @"1512313756";
    [ZXCheckAppItunesVersionManager checkAppStoreNewVersionWithAppleID:appId success:^(BOOL isHaveNewVersion,CAIItunesModel *itunesModel) {
        [MBProgressHUD zx_hideHUD];
        if (isHaveNewVersion) {
            [UIAlertController zx_presentGeneralAlertInViewController:weakSelf withTitle:[NSString stringWithFormat:@"发现新版本%@",itunesModel.version] message:itunesModel.releaseNotes cancelButtonTitle:@"取消" cancleHandler:nil doButtonTitle:@"确定" doHandler:^(UIAlertAction * _Nonnull action) {
                [UIApplication zx_openURLToItunesForApplicationIdentifier:appId];
            }];
        }else{
            [MBProgressHUD zx_showError:@"已经是最新版本了"];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [MBProgressHUD zx_showError:error.localizedDescription toView:nil];
    }];
}




@end

